package com.dds.system.service.app.impl;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dds.common.config.AppInterfaceConfig;
import com.dds.common.utils.http.HttpUtils;
import com.dds.common.utils.sign.Md5Utils;
import com.dds.system.domain.admin.AdminUserOperation;
import com.dds.system.domain.app.AppUser;
import com.dds.system.domain.union.UnionShopCategory;
import com.dds.system.mapper.admin.AdminUserOperationMapper;
import com.dds.system.mapper.app.AppUserMapper;
import com.dds.system.mapper.union.UnionShopCategoryMapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dds.system.mapper.app.AppMessageDefineMapper;
import com.dds.system.domain.app.AppMessageDefine;
import com.dds.system.service.app.IAppMessageDefineService;

import static com.dds.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * APP中的消息定义Service业务层处理
 *
 * @author gaolianjie
 * @date 2021-04-13
 */
@Service
public class AppMessageDefineServiceImpl implements IAppMessageDefineService {
    @Autowired
    private AppMessageDefineMapper appMessageDefineMapper;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private AdminUserOperationMapper adminUserOperationMapper;

    @Autowired
    private UnionShopCategoryMapper unionShopCategoryMapper;

    @Autowired
    private AppInterfaceConfig appInterfaceConfig;

    /**
     * 查询APP中的消息定义
     *
     * @param messageId APP中的消息定义ID
     * @return APP中的消息定义
     */
    @Override
    public AppMessageDefine selectAppMessageDefineById(Long messageId) {
        AppMessageDefine appMessageDefine = appMessageDefineMapper.selectAppMessageDefineById(messageId);

        appMessageDefine.setMessageSendCondition(
                arrangeMessageSendCondition(appMessageDefine.getMessageSendCondition())
        );

        return appMessageDefine;
    }

    /**
     * 查询APP中的消息定义列表
     *
     * @param appMessageDefine APP中的消息定义
     * @return APP中的消息定义
     */
    @Override
    public List<AppMessageDefine> selectAppMessageDefineList(AppMessageDefine appMessageDefine) {
        return appMessageDefineMapper.selectAppMessageDefineList(appMessageDefine);
    }

    /**
     * 新增APP中的消息定义
     *
     * @return 结果
     */
    @Override
    public int insertAppMessageDefine(Map<String, Object> params) {
        String messageSendCondition = arrangeMessageSendCondition(params);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        Date messageDate = null;
        try {
            messageDate = simpleDateFormat.parse(params.get("messageDate").toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        AppMessageDefine appMessageDefine = AppMessageDefine.of()
                .setMessageTitle(params.get("messageTitle").toString())
                .setMessageDesc(params.get("messageDesc").toString())
                .setMessageDate(messageDate)
                .setMessageSendCondition(messageSendCondition)
                .setMessageIsPush(params.get("messageIsPush").toString())
                .setMessageContent(params.get("messageContent").toString())
                .setMessageCate(Integer.parseInt(params.get("messageCate").toString()))
                .setMessageType(Integer.parseInt(params.get("messageType").toString()))
                .setMessageTypeValue(params.get("messageTypeValue") == null ? null : params.get("messageTypeValue").toString())
                .setMessageImgUrl(params.get("messageImgUrl") == null ? null : params.get("messageImgUrl").toString());

        return appMessageDefineMapper.insertAppMessageDefine(appMessageDefine);
    }

    /**
     * 修改APP中的消息定义
     *
     * @param appMessageDefine APP中的消息定义
     * @return 结果
     */
    @Override
    public int updateAppMessageDefine(AppMessageDefine appMessageDefine) {
        return appMessageDefineMapper.updateAppMessageDefine(appMessageDefine);
    }

    /**
     * 格式化表单传递的condition
     * @param appMessageDefine
     * @return
     */
    private String arrangeMessageSendCondition(Map<String, Object> appMessageDefine) {
        Map<String, Object> conditionSelect = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        if (appMessageDefine.get("messageSendCondition").equals(1)) {
            map.put("operation", appMessageDefine.get("operation"));
            map.put("industry", appMessageDefine.get("industry"));
            map.put("sendType", appMessageDefine.get("sendType"));

            conditionSelect.put("conditionSelect", map);
        } else {
            if (appMessageDefine.get("radioOption").equals(1)) {
                conditionSelect.put("sepcUser", appMessageDefine.get("user"));
            } else {
                List<String> sepcUser = new ArrayList<>();
                sepcUser.add(appMessageDefine.get("sepcUser").toString());
                conditionSelect.put("sepcUser", sepcUser);
            }
        }
        System.out.println(JSON.toJSONString(conditionSelect));
        return JSON.toJSONString(conditionSelect);
    }

    /**
     * 转换数据库condition
     * @param conditionJson
     * @return
     */
    private String arrangeMessageSendCondition(String conditionJson) {
        String content = "";
        JSONObject condition = JSON.parseObject(conditionJson);
        if (condition.containsKey("sepcUser")) {
            List<String> userIds = JSON.parseArray(condition.getJSONArray("sepcUser").toJSONString(), String.class);
            List<AppUser> lstAppUser = appUserMapper.selectAppUserByIds(userIds);

            content += "指定用户：";

            for (AppUser user : lstAppUser) {
                content += "（" + user.getUsername() + "）";
            }
        } else if (condition.containsKey("conditionSelect")) {
            List<String> operationIds = JSON.parseArray(
                    condition.getJSONObject("conditionSelect").getJSONArray("operation").toJSONString(),
                    String.class);

            List<String> industryIds = JSON.parseArray(
                    condition.getJSONObject("conditionSelect").getJSONArray("industry").toJSONString(),
                    String.class
            );

            Integer sendType = condition.getJSONObject("conditionSelect").getInteger("sendType");

            List<AdminUserOperation> lstOperation = adminUserOperationMapper.selectListByIds(operationIds);
            content += "区域：（";
            for (AdminUserOperation operation : lstOperation) {
                content += operation.getOperationName() + "，";
            }

            content += "）行业（";
            List<UnionShopCategory> lstCategory = unionShopCategoryMapper.selectListByIds(industryIds);
            for (UnionShopCategory category : lstCategory) {
                content += category.getCateName() + "，";
            }

            content += "）发送范围（";
            if (sendType == 1) {
                content += "全部）";
            } else {
                content += "商家管理员）";
            }
        } else {
            content += "未知";
        }

        return content;
    }

    /**
     * 批量删除APP中的消息定义
     *
     * @param messageIds 需要删除的APP中的消息定义ID
     * @return 结果
     */
    @Override
    public int deleteAppMessageDefineByIds(Long[] messageIds) {
        return appMessageDefineMapper.deleteAppMessageDefineByIds(messageIds);
    }

    /**
     * 删除APP中的消息定义信息
     *
     * @param messageId APP中的消息定义ID
     * @return 结果
     */
    @Override
    public int deleteAppMessageDefineById(Long messageId) {
        return appMessageDefineMapper.deleteAppMessageDefineById(messageId);
    }

    @Override
    public boolean sendMessage(Long messageId) {
        String result = HttpUtils.sendPost(
                appInterfaceConfig.getWebUrl() + "/rest/back/message/send",
                "messageId=" + messageId + "&secret=" + Md5Utils.hash(messageId.toString() + "dds.com"));

        Map map = JSON.parseObject(result, Map.class);

        if (Integer.parseInt(map.get("code").toString()) != 0) {
            return false;
        }

        return true;
    }
}
